capture program drop distIVbounds

program distIVbounds 
	syntax varlist(min=2) , d(varlist) z(varlist) [mean variance quantile(real .5)]
	
	dis in red "Estimation using instrument exogeneity"
	
	gettoken Y X:varlist
 
 	*generating influence functions and their upper and lower bounds
	*********preparation of estimation - this is independent of IV vs panel, and of regression method******** 
	generateIF Y, `mean' `variance' quantile(`quantile')
	*generating upper and lower bounds on potential outcome influence functions
	tempname IF1upper IF1lower IF0upper IF0lower
	quietly gen `IF1upper' = D*IF + (1-D)*IFupper
	quietly gen `IF1lower' = D*IF + (1-D)*IFlower
	quietly gen `IF0upper' = (1-D)*IF + D*IFupper
	quietly gen `IF0lower' = (1-D)*IF + D*IFlower
	************************************************************************
	
	
	
	*******running regressions to estimate bounds on gphi******************************
	***assumes: we have binary instrument Z, positively correlated with D, exogenous given X
	tempname ASF1upper ASF1lower ASF0upper ASF0lower
	
	quietly regress `IF1upper' `X' if (Z==1)
	predict `ASF1upper', xb
	quietly regress `IF1lower' `X' if (Z==1)
	predict `ASF1lower', xb

	quietly regress `IF0upper' `X' if (Z==0)
	predict `ASF0upper', xb
	quietly regress `IF0lower' `X' if (Z==0)
	predict `ASF0lower', xb

	gen gphiupper=`ASF1upper'-`ASF0lower'
	gen gphilower=`ASF1lower'-`ASF0upper'
	gen w=gphiupper-gphilower
	*****************************************************
	
	
end
